# -*- coding: utf-8 -*-
"""
心理咨询师服务系统 - 主路由
"""

from flask import render_template, jsonify, current_app
from app.main import bp
from app import db


@bp.route('/')
@bp.route('/index')
def index():
    """首页"""
    return render_template('index.html')


@bp.route('/health')
def health_check():
    """健康检查"""
    try:
        # 检查数据库连接
        from app import db
        db.session.execute('SELECT 1')
        
        return jsonify({
            'status': 'healthy',
            'database': 'connected',
            'timestamp': current_app.config.get('STARTUP_TIME', 'unknown')
        })
    except Exception as e:
        current_app.logger.error(f'健康检查失败: {str(e)}')
        return jsonify({
            'status': 'unhealthy',
            'database': 'disconnected',
            'error': str(e)
        }), 500


@bp.route('/scales')
def scales():
    """量表收集页面"""
    return render_template('scales.html')


@bp.route('/membership')
def membership():
    """会员方案页面"""
    return render_template('membership.html')


@bp.route('/login')
def login():
    """登录页面"""
    return render_template('login.html')


@bp.route('/register')
def register():
    """注册页面"""
    return render_template('register.html')


@bp.route('/admin-portal')
def admin_portal():
    """管理员门户"""
    return render_template('admin/login.html')


@bp.route('/admin-dashboard')
def admin_dashboard():
    """管理员仪表板"""
    from flask_jwt_extended import jwt_required, get_jwt_identity
    from app.models import AdminUser, Assessment
    from app.utils.decorators import admin_required
    from datetime import datetime, timedelta
    from sqlalchemy import func, desc
    
    try:
        # 模拟统计数据（实际应该从数据库获取）
        stats = {
            'total_users': 1250,
            'user_growth': 12.5,
            'today_assessments': 45,
            'assessment_growth': 8.3,
            'risk_users': 23,
            'risk_increase': 3,
            'premium_members': 156,
            'member_growth': 15.2
        }
        
        # 获取最近的测评记录
        recent_assessments = Assessment.query.order_by(desc(Assessment.created_at)).limit(10).all()
        
        # 模拟当前管理员信息
        current_admin = type('MockAdmin', (), {
            'username': 'admin',
            'last_login_at': datetime.now() - timedelta(hours=2)
        })()
        
        return render_template('admin/dashboard.html', 
                             stats=stats, 
                             recent_assessments=recent_assessments,
                             current_admin=current_admin)
    except Exception as e:
        current_app.logger.error(f'管理员仪表板加载失败: {str(e)}')
        # 返回基本模板，避免错误
        return render_template('admin/dashboard.html', 
                             stats={'total_users': 0, 'user_growth': 0, 'today_assessments': 0, 
                                   'assessment_growth': 0, 'risk_users': 0, 'risk_increase': 0,
                                   'premium_members': 0, 'member_growth': 0}, 
                             recent_assessments=[],
                             current_admin=type('MockAdmin', (), {
                                 'username': 'admin',
                                 'last_login_at': None
                             })())


@bp.route('/results')
def results():
    """查看结果页面"""
    return render_template('results.html')


@bp.route('/api/scales/featured')
def featured_scales():
    """获取推荐量表"""
    # 返回推荐的量表数据
    featured_scales_data = [
        {
            'id': 1,
            'name': 'PHQ-9',
            'full_name': 'Patient Health Questionnaire-9',
            'category': '抑郁筛查',
            'description': '9个条目，评估抑郁症状严重程度，包含自杀风险评估'
        },
        {
            'id': 2,
            'name': 'GAD-7',
            'full_name': 'Generalized Anxiety Disorder 7-item',
            'category': '焦虑筛查',
            'description': '7个条目，广泛性焦虑障碍专业筛查工具'
        },
        {
            'id': 3,
            'name': 'SCL-90',
            'full_name': 'Symptom Checklist-90',
            'category': '综合症状',
            'description': '90个条目，9个因子，全面症状评估'
        },
        {
            'id': 4,
            'name': '16PF',
            'full_name': 'Sixteen Personality Factor',
            'category': '人格测评',
            'description': '16个人格因子，全面人格特质评估'
        }
    ]
    
    return jsonify({
        'success': True,
        'data': featured_scales_data
    })


@bp.route('/api/info')
def api_info():
    """API信息"""
    return jsonify({
        'name': '心理咨询师服务系统 API',
        'version': '1.0.0',
        'description': '专业的心理量表管理和测评平台',
        'endpoints': {
            'auth': '/api/auth/*',
            'users': '/api/users/*',
            'scales': '/api/scales/*',
            'assessments': '/api/assessments/*',
            'admin': '/api/admin/*',
            'members': '/api/members/*',
            'system': '/api/system/*'
        },
        'documentation': '/api/docs'
    })


@bp.route('/admin-users')
def admin_users():
    """管理员用户管理页面"""
    from flask import request
    from app.models import User, UserMembership
    from sqlalchemy import or_, func, desc
    from datetime import datetime, timedelta
    
    try:
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = 20
        search = request.args.get('search', '')
        status = request.args.get('status', '')
        member_type = request.args.get('member_type', '')
        time_filter = request.args.get('time_filter', '')
        
        # 构建查询
        query = User.query.join(UserMembership, User.id == UserMembership.user_id, isouter=True)
        
        # 搜索条件
        if search:
            search_pattern = f'%{search}%'
            query = query.filter(
                or_(
                    User.username.like(search_pattern),
                    User.email.like(search_pattern),
                    User.phone.like(search_pattern)
                )
            )
        
        # 状态筛选
        if status == 'active':
            query = query.filter(User.is_active == True, User.is_verified == True)
        elif status == 'inactive':
            query = query.filter(User.is_active == False)
        elif status == 'unverified':
            query = query.filter(User.is_verified == False)
        
        # 会员类型筛选
        if member_type:
            query = query.filter(UserMembership.plan_type == member_type)
        
        # 时间筛选
        if time_filter:
            now = datetime.utcnow()
            if time_filter == 'today':
                start_date = now.replace(hour=0, minute=0, second=0, microsecond=0)
                query = query.filter(User.created_at >= start_date)
            elif time_filter == 'week':
                start_date = now - timedelta(days=7)
                query = query.filter(User.created_at >= start_date)
            elif time_filter == 'month':
                start_date = now - timedelta(days=30)
                query = query.filter(User.created_at >= start_date)
            elif time_filter == 'year':
                start_date = now - timedelta(days=365)
                query = query.filter(User.created_at >= start_date)
        
        # 排序
        query = query.order_by(desc(User.created_at))
        
        # 分页
        pagination = query.paginate(
            page=page, per_page=per_page, error_out=False
        )
        users = pagination.items
        
        # 统计数据
        total_users = User.query.count()
        active_users = User.query.filter(User.is_active == True, User.is_verified == True).count()
        
        # 今日新增用户
        today = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
        new_users_today = User.query.filter(User.created_at >= today).count()
        
        # 付费会员数
        premium_users = User.query.join(UserMembership).filter(
            UserMembership.plan_type.in_(['professional', 'institution', 'research'])
        ).count()
        
        # 计算增长率（模拟数据）
        user_growth = 12.5
        daily_avg = 2.5
        active_rate = round((active_users / total_users * 100), 1) if total_users > 0 else 0
        premium_rate = round((premium_users / total_users * 100), 1) if total_users > 0 else 0
        
        stats = {
            'total_users': total_users,
            'user_growth': user_growth,
            'new_users_today': new_users_today,
            'daily_avg': daily_avg,
            'active_users': active_users,
            'active_rate': active_rate,
            'premium_users': premium_users,
            'premium_rate': premium_rate
        }
        
        return render_template('admin/users.html', 
                             users=users,
                             pagination=pagination,
                             stats=stats)
                             
    except Exception as e:
        current_app.logger.error(f'用户管理页面加载失败: {str(e)}')
        # 返回空数据避免错误
        return render_template('admin/users.html', 
                             users=[],
                             pagination=type('MockPagination', (), {
                                 'total': 0, 'pages': 0, 'page': 1,
                                 'has_prev': False, 'has_next': False,
                                 'prev_num': None, 'next_num': None,
                                 'iter_pages': lambda: []
                             })(),
                             stats={
                                 'total_users': 0, 'user_growth': 0,
                                 'new_users_today': 0, 'daily_avg': 0,
                                 'active_users': 0, 'active_rate': 0,
                                 'premium_users': 0, 'premium_rate': 0
                             })


@bp.route('/admin-members')
def admin_members():
    """管理员会员管理页面"""
    from flask import request
    from app.models import User, UserMembership
    from sqlalchemy import func
    from datetime import datetime, timedelta, date
    
    try:
        # 统计数据
        stats = {
            'basic_members': UserMembership.query.filter_by(plan_type='basic', status='active').count(),
            'professional_members': UserMembership.query.filter_by(plan_type='professional', status='active').count(),
            'institution_members': UserMembership.query.filter_by(plan_type='institution', status='active').count(),
            'research_members': UserMembership.query.filter_by(plan_type='research', status='active').count(),
            'monthly_revenue': 0,
            'expiring_soon': 0
        }
        
        # 计算本月收入
        current_month = date.today().replace(day=1)
        monthly_revenue = db.session.query(
            func.sum(UserMembership.payment_amount)
        ).filter(
            UserMembership.created_at >= current_month,
            UserMembership.status == 'active'
        ).scalar() or 0
        stats['monthly_revenue'] = float(monthly_revenue)
        
        # 计算即将到期的会员数
        week_later = date.today() + timedelta(days=7)
        expiring_soon = UserMembership.query.filter(
            UserMembership.status == 'active',
            UserMembership.end_date <= week_later,
            UserMembership.end_date >= date.today()
        ).count()
        stats['expiring_soon'] = expiring_soon
        
        # 分页信息（初始为空，由JavaScript加载）
        pagination = {
            'total': 0,
            'pages': 0,
            'page': 1,
            'has_prev': False,
            'has_next': False
        }
        
        return render_template('admin/members.html', 
                             stats=stats,
                             pagination=pagination)
                             
    except Exception as e:
        current_app.logger.error(f'会员管理页面加载失败: {str(e)}')
        # 返回基本数据避免错误
        return render_template('admin/members.html', 
                             stats={
                                 'basic_members': 0,
                                 'professional_members': 0,
                                 'institution_members': 0,
                                 'research_members': 0,
                                 'monthly_revenue': 0,
                                 'expiring_soon': 0
                             },
                             pagination={
                                 'total': 0, 'pages': 0, 'page': 1,
                                 'has_prev': False, 'has_next': False
                             })


@bp.route('/admin-scales')
def admin_scales():
    """管理员量表管理页面"""
    return render_template('admin/scales.html', active_page='scales')


@bp.route('/admin-assessments')
def admin_assessments():
    """管理员测评记录管理页面"""
    return render_template('admin/assessments.html', active_page='assessments')


@bp.route('/admin-member-publications')
def admin_member_publications():
    """管理员会员发布管理页面"""
    return render_template('admin/member_publications.html', active_page='member_publications')


@bp.route('/admin/users/<int:user_id>')
def admin_user_detail(user_id):
    """管理员用户详情页面"""
    from app.models import User, UserMembership, Assessment
    from sqlalchemy import desc
    
    try:
        user = User.query.get_or_404(user_id)
        
        # 获取用户会员信息
        membership = UserMembership.query.filter_by(user_id=user_id, status='active').first()
        
        # 获取用户最近的测评记录
        recent_assessments = Assessment.query.filter_by(user_id=user_id).order_by(desc(Assessment.created_at)).limit(10).all()
        
        return render_template('admin/user-detail.html', 
                             user=user, 
                             membership=membership,
                             recent_assessments=recent_assessments,
                             active_page='users')
    except Exception as e:
        current_app.logger.error(f'用户详情页面加载失败: {str(e)}')
        from flask import abort
        abort(404)


@bp.route('/admin/scales/create')
def admin_scale_create():
    """管理员量表创建页面"""
    return render_template('admin/scale-create.html', active_page='scales')


@bp.route('/admin/scales/<int:scale_id>')
def admin_scale_detail(scale_id):
    """管理员量表详情页面"""
    from app.models import Scale, Assessment
    from app.models.assessment import AssessmentStatus
    from sqlalchemy import func, desc
    
    try:
        scale = Scale.query.get_or_404(scale_id)
        
        # 获取量表统计信息
        total_assessments = Assessment.query.filter_by(scale_id=scale_id).count()
        completed_assessments = Assessment.query.filter_by(scale_id=scale_id, status=AssessmentStatus.COMPLETED).count()
        
        # 获取最近的测评记录
        recent_assessments = Assessment.query.filter_by(scale_id=scale_id).order_by(desc(Assessment.created_at)).limit(10).all()
        
        stats = {
            'total_assessments': total_assessments,
            'completed_assessments': completed_assessments,
            'completion_rate': round((completed_assessments / total_assessments * 100), 1) if total_assessments > 0 else 0
        }
        
        return render_template('admin/scale-detail.html', 
                             scale=scale, 
                             stats=stats,
                             recent_assessments=recent_assessments,
                             active_page='scales')
    except Exception as e:
        current_app.logger.error(f'量表详情页面加载失败: {str(e)}')
        from flask import abort
        abort(404)


@bp.route('/admin/scales/<int:scale_id>/edit')
def admin_scale_edit_with_id(scale_id):
    """管理员量表编辑页面（带ID）"""
    from app.models import Scale
    try:
        scale = Scale.query.get_or_404(scale_id)
        return render_template('admin/scale-edit.html', scale_id=scale_id, scale=scale, active_page='scales')
    except Exception as e:
        current_app.logger.error(f'量表编辑页面加载失败: {str(e)}')
        from flask import abort
        abort(404)


@bp.route('/admin/scale-edit')
def admin_scale_edit():
    """量表编辑页面"""
    from flask import request
    scale_id = request.args.get('id')
    return render_template('admin/scale-edit.html', scale_id=scale_id, active_page='scales')


@bp.route('/admin/scale-design')
def admin_scale_design():
    """题目设计页面"""
    return render_template('admin/scale-design.html', active_page='scales')


@bp.route('/scales/<int:scale_id>/preview')
def scale_preview(scale_id):
    """量表预览页面"""
    from flask import request
    try:
        from app.models import Scale
        scale = Scale.query.get(scale_id)
        if not scale:
            from flask import abort
            abort(404)
        
        return render_template('members/scale_preview.html', scale_id=scale_id, scale=scale)
    except Exception as e:
        current_app.logger.error(f'量表预览页面加载失败: {str(e)}')
        from flask import abort
        abort(500)


@bp.route('/scales/<int:scale_id>/assessment')
def scale_assessment(scale_id):
    """量表测评页面"""
    try:
        # 简化版本，支持匿名用户访问
        return render_template('members/assessment.html', scale_id=scale_id)
    except Exception as e:
        current_app.logger.error(f'量表测评页面加载失败: {str(e)}')
        # 返回一个基本的错误页面
        return f'''
        <!DOCTYPE html>
        <html>
        <head>
            <title>页面加载失败</title>
            <meta charset="UTF-8">
        </head>
        <body style="font-family: Arial; text-align: center; padding: 50px;">
            <h2>页面加载失败</h2>
            <p>量表测评页面暂时无法访问，请稍后重试。</p>
            <p>Scale ID: {scale_id}</p>
            <p><a href="/scales">返回量表列表</a></p>
        </body>
        </html>
        ''', 500


@bp.route('/assessments/<int:assessment_id>/results')
def assessment_results(assessment_id):
    """评测结果页面"""
    try:
        # 支持匿名用户查看结果
        return render_template('members/assessment_results.html', assessment_id=assessment_id)
    except Exception as e:
        current_app.logger.error(f'评测结果页面加载失败: {str(e)}')
        return f'''
        <!DOCTYPE html>
        <html>
        <head>
            <title>结果加载失败</title>
            <meta charset="UTF-8">
        </head>
        <body style="font-family: Arial; text-align: center; padding: 50px;">
            <h2>结果加载失败</h2>
            <p>评测结果页面暂时无法访问，请稍后重试。</p>
            <p>Assessment ID: {assessment_id}</p>
            <p><a href="/scales">返回量表列表</a></p>
        </body>
        </html>
        ''', 500